package com.controller;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.entity.Article;
import com.entity.Category;
import com.entity.Tag;
import com.entity.User;
import com.github.pagehelper.PageInfo;
import com.service.ArticleService;
import com.service.CategoryService;
import com.service.TagService;


import cn.hutool.http.HtmlUtil;



@Controller @RequestMapping("/article")
public class ArticleController {
	
	@Resource
	ArticleService articleService;
	
	@Resource
	CategoryService categoryService;
	
	@Resource
	TagService TagService;
	
	@Resource
	RedisTemplate redisTemplate;
	
	//显示文章列表并分页
	@RequestMapping("")      //false:参数pageIndex可不传不会报错 1:没有参数传递时会传1
	public String index(@RequestParam(required= false,defaultValue="1") Integer pageIndex,
						@RequestParam(required= false,defaultValue="5") Integer pageSize,ModelMap m) {
		
		PageInfo<Article> pageInfo = articleService.getPageArticleList(pageIndex,pageSize);
		m.put("pageInfo",pageInfo);
		m.put("pageUrlPrefix","article?pageIndex"); //把前缀传给分页导航页（page.jsp）
	
		return "Article/article-list";
	}
	
	//去添加文章页面之前先查询分类、标签列表      当URl重名时，当提出的请求为get(从超链接发起的请求或从浏览器地址栏里发起)才会运行此方法用于（/article/add）
	@RequestMapping(value="/add" , method=RequestMethod.GET)
	public String gotoAddPage(ModelMap m) {
		//查询分类信息
		List<Category> categoryList=categoryService.listCategory();
		
		//查询标签信息
		List<Tag> tagList= TagService.listTag();
		

		m.put("categoryList",categoryList);
		m.put("tagList",tagList);
		return "Article/article-add";
	}
	
	//文章草稿
	@RequestMapping(value="/Draft",method=RequestMethod.POST)
	public String draft(HttpServletRequest request) {
		Article article = new Article();
		article.setArticleStatus(0);
		article.setArticleTitle(request.getParameter("articleTitle"));
		article.setArticleContent(request.getParameter("articleContent"));
		articleService.addArticleDraft(article);
		
		return "redirect:../article"; 
	}
	
	//添加文章     当URl重名时，提出的请求为POST(从表单中且form的method为POST发起)才会运行此方法用于（/article/add）
	@RequestMapping(value="/add" , method=RequestMethod.POST)
	public String add(ModelMap m,HttpServletRequest request) {
		Article article = new Article();
		
		//取当前用户的id
		User user =(User) request.getSession().getAttribute("session_user");
		if(user!=null) {
			article.setArticleUserId(user.getUserId());
		}
		article.setArticleTitle(request.getParameter("articleTitle"));
		article.setArticleContent(request.getParameter("articleContent"));
		article.setArticleStatus(Integer.parseInt(request.getParameter("articleStatus")));
		String str = HtmlUtil.cleanHtmlTag(article.getArticleContent());//cleanHtmlTag过滤tag标签提取里边的内容
		article.setArticleSummary(str.length()>150?str.substring(0,150):str);//如果文章内容大于150字则只选取150字
		article.setArticleCreateTime(new Date());
		article.setArticleUpdateTime(new Date());
		article.setArticleViewCount(0);
		article.setArticleLikeCount(0);
		article.setArticleCommentCount(0);
		article.setArticleOrder(1);
		
		//一级分类的id
		int parentCateId = Integer.parseInt(request.getParameter("articleParentCategoryId"));
		
		//二级分类的id
		int childCateId = Integer.parseInt(request.getParameter("articleChildCategoryId"));
		
		//把上面的两个分类装到list中
		List<Category> categoryList = new ArrayList<>(2);
		categoryList.add(new Category(parentCateId));
		categoryList.add(new Category(childCateId));
		
		//所选择的标签列表返回一个数组
		String [] tagIds = request.getParameterValues("articleTagIds"); //所选标签id
		List<Tag> tagList=new ArrayList<>();
		for(String tagId:tagIds) {//把所选标签id类型转换成整型遍历放到list中
			tagList.add(new Tag(Integer.parseInt(tagId)));
		}
		
		//把分类和标签信息添加到article中
		article.setCategoryList(categoryList);
		article.setTagList(tagList);
		
		//添加文章
		articleService.addArticle(article);
		
		//转到列表页时只有添加操作没有查询操作 所以需要请求转发到查询方法index里再调用一次index
		return "redirect:../article"; //使用重定向在删除时不会认为有安全问题，被拦截回滚。
	}

	//富文本编辑器上传照片
	@RequestMapping("/uploadimg") @ResponseBody //将返回结果改成json格式
	public String uploadFile(MultipartHttpServletRequest request) throws Exception {
		//imgFile从前端传来的文件
		MultipartFile file = request.getFile("imgFile");
		//生成一个随机的文件名
		String newName = UUID.randomUUID().toString();
		File destFile = new File("D://imguploads//"+newName+".jpg"); //放置照片空间
		file.transferTo(destFile); //将file传输给destFile空间
		String path="http://localhost:8080/uploads/"+newName+".jpg";
		
		//json格式所有参数需要用""括起来，{}外双引号导致里面双引号就近匹配，所有里面双引号需要用\转义
		return "{\"error\":0,\"url:\""+path+"\"}";
	}
	
	//全部文章里点文章标题跳转这个方法
	@RequestMapping("content/{id}")
	public String Content(@PathVariable("id") Integer id,ModelMap m) {
		
		Article article = articleService.getArticleById(id);
		List<Tag> tag = TagService.getTagById(id);
		
		m.put("article", article);
		m.put("tag", tag);
		return "Article/article-content";
	}
	
	//全部文章里编辑跳转到这个方法
	@RequestMapping(value="/update/{id}",method=RequestMethod.GET)
	public String gotoUpdatePage(@PathVariable("id") Integer id,ModelMap m) {
		Article article = articleService.getArticleById(id);
		List<Category> categoryList=categoryService.listCategory();
		List<Tag> tagList= TagService.listTag();
		m.put("categoryList",categoryList);
		m.put("tagList",tagList);
		m.put("article", article);
		return "Article/article-update";
	}

	//全部文章编辑提交表单跳转到这个方法
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public String UpdateArticle(HttpServletRequest request,ModelMap m) {
		//不能使用传统更新，因为分类关联表一个文章Id对应两个分类id，应该先删除后添加
		articleService.deleteArticle(Integer.parseInt(request.getParameter("articleId")));	
		
		
		Article article = new Article();
		article.setArticleId(Integer.parseInt(request.getParameter("articleId")));
		article.setArticleTitle(request.getParameter("articleTitle"));
		article.setArticleContent(request.getParameter("articleContent"));
		article.setArticleCreateTime(new Date());
		article.setArticleUpdateTime(new Date());
		
		
		String str = HtmlUtil.cleanHtmlTag(article.getArticleContent());//cleanHtmlTag过滤tag标签提取里边的内容
		article.setArticleSummary(str.length()>150?str.substring(0,150):str);//如果文章内容大于150字则只选取150字
		
		int ParentCategoryId = Integer.parseInt(request.getParameter("articleParentCategoryId"));
		int ChildCategoryId = Integer.parseInt(request.getParameter("articleChildCategoryId"));
		List<Category> Category = new ArrayList<>(2);
		Category.add(new Category(ParentCategoryId));
		Category.add(new Category(ChildCategoryId));
		article.setCategoryList(Category);
		
		//加上Values所选择的标签列表返回一个数组
		String [] tagIds = request.getParameterValues("articleTagIds");
		List<Tag> TagList = new ArrayList<>();
		for(String tagId:tagIds) {
			TagList.add(new Tag(Integer.parseInt((tagId))));
		}	
		article.setTagList(TagList);
		
		article.setArticleOrder(Integer.parseInt(request.getParameter("articleOrder")));
		article.setArticleStatus(Integer.parseInt(request.getParameter("articleStatus")));
		
		articleService.addArticle(article);;
		
		return "redirect:../article";
	}
	
	
	//全部文章删除跳转
	
	@RequestMapping("/delete/{id}")
	public void deleteArticle(@PathVariable("id") Integer id) {
	 
		articleService.deleteArticle(id);	
	}
}
















































